import React, { useEffect, useCallback } from 'react';
import { Icon, Tooltip } from 'antd';
import {
  // ArrayTable, // formily 1 不支持分页，用自定义(自定义的也尚未完成分页支持)
  Input,
  Checkbox,
  Select,
} from '@formily/antd-components'
import { SchemaForm, createFormActions, FormSpy } from "@formily/antd";
import { codePattern } from '@/pages/flowmanage/formbuilder';
import ArrayTable, { paginationContext } from './ArrayTable';
import styles from './ColumnSettingArrayTable.less';

const renderNull = () => null;
const actions = createFormActions();

const ColumnSettingArrayTable = (props) => {
  const { getFormAction, value } = props;


  useEffect(() => {
    if (getFormAction) {
      getFormAction(actions);
    }
  }, []);


  return (
    <SchemaForm
      className={styles.root}
      initialValues={value}
      actions={actions}
      components={{
        arrayTable: ArrayTable,
        input: Input,
        select: Select,
        checkbox: Checkbox,
      }}
      schema={{
        "version": "1.0",
        "type": "object",
        "properties": {
          "columns": {
            "version": "1.0",
            "key": "columns",
            "title": " ",
            "name": "columns",
            "maxItems": 20,
            "type": "array",
            "x-component": "arraytable",
            "x-props": {
              "labelCol": { span: 0 },
              "wrapperCol": { "span": 24 },
              "colon": false,
            },
            "x-component-props": {
              "operationsWidth": 30,
              "operations": { "title": "操作" },
              "renderMoveDown": "{{renderNull}}",
              "renderMoveUp": "{{renderNull}}",
              "renderRemove": "{{renderRemove}}",
              "renderAddition": "{{renderAddition}}",
              // 目前不支持分页，不要设置其他值
              // 遗留问题:
              // 分页后未渲染(即不在当前页码内）的表单域在submit时无法
              // 拿到值。
              "pageSize": 20,
            },
            "items": {
              "version": "1.0",
              "type": "object",
              "properties": {
                "title": {
                  "version": "1.0",
                  "key": "title",
                  "name": "title",
                  "x-component": "input",
                  "x-rules": {
                    "required": true,
                    "message": "请输入列标题",
                  },
                  "x-component-props": {
                    "maxLength": 15,
                  },
                  "description": "",
                  "title": "列标题",
                  "x-index": 1,
                  "x-props": {
                    "width": 243,
                  },
                },
                "key": {
                  "version": "1.0",
                  "key": "key",
                  "name": "key",
                  "x-component": "input",
                  "x-rules": [
                    { "required": true, "message": "请输入列编码" },
                    { "pattern": codePattern, "message": "字母或_开头，包含字母，数字及'-_'" },
                  ],
                  "x-component-props": {
                    "maxLength": 20,
                  },
                  "description": "",
                  "title": "列编码",
                  "x-index": 2,
                  "x-props": {
                    "width": 243,
                  },
                },
                "type": {
                  "version": "1.0",
                  "key": "type",
                  "name": "type",
                  "x-component": "select",
                  "title": "列类型",
                  "enum": [
                    { "label": "填空项", "value": "input" },
                    { "label": "下拉单选", "value": "select" },
                  ],
                  "default": 'input',
                  "x-index": 3,
                  "x-rules": {
                    "required": true,
                    "message": "请选择列类型",
                  },
                  "x-linkages": [
                    {
                      "type": "value:visible",
                      "target": "..[].options",
                      "condition": "{{ $self.value === 'select' }}",
                    },
                  ],
                  "x-props": {
                    "width": 147,
                  },
                },
                "options": {
                  "version": "1.0",
                  "key": "options",
                  "name": "options",
                  "x-component": "input",
                  "x-component-props": {
                    "placeholder": '添加选项，以分号分割',
                    "maxLength": 300,
                    // "allowClear": true,
                  },
                  "x-rules": {
                    "required": true,
                    "message": "请输入选项",
                  },
                  "title": "选项设置",
                  "x-index": 4,
                  "x-props": {
                    "width": 245,
                  },
                },
                "required": {
                  "version": "1.0",
                  "key": "required",
                  "name": "required",
                  "x-component": "checkbox",
                  "title": "必填",
                  "x-index": 5,
                },
              },
            },
          },
        },
      }}
      expressionScope={{
        renderNull,
        renderAddition: () => (
          <Tooltip placement="top" title="最多可添加20列">
            <a onClick={e => e.preventDefault()}>
              <Icon type="plus" />
              &nbsp;&nbsp;
              添加一列
            </a>
          </Tooltip>
        ),
        renderRemove: useCallback((index) => {
          const mutators = actions.createMutators('columns')
            return (
              <paginationContext.Consumer>
                { ({ current, pageSize, setPagination, currentDataSource }) => (
                  <FormSpy
                    selector={[['onFieldValueChange', 'columns']]}
                  >
                    {({ state }) => {
                      return (state.value && state.value.length > 1) ? (
                        <a
                          onClick={(e) => {
                            e.preventDefault();
                            const idx = (current - 1) * pageSize + index;
                            mutators.remove(idx)
                            if (pageSize && current > 1 && currentDataSource.length ===1) {
                              setPagination({
                                current: current - 1,
                                pageSize,
                              });
                            }
                          }}
                        >
                          删除
                        </a>
                      ) : null
                    }}
                  </FormSpy>
                )}
              </paginationContext.Consumer>
            )
        }, [actions]),
      }}
    />
    /*
      <FormButtonGroup>
        <Button onCancel={onCancel}>取消</Button>
        <Submit
          type="primary"
          showLoading
          onSubmit={(values) => {
            console.log(values);
            onOk(values);
          }}
        >
          确认
        </Submit>
      </FormButtonGroup>
    </SchemaForm>
    */

  );
}

export default ColumnSettingArrayTable;
